package com.atguigu.gmall.mq.receiver;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class ConfirmReceiver {

    @RabbitListener(queues = "queue1")
    public void message1(String message){
        System.out.println("接收到的消息1:"+message);
    }


    @RabbitListener(bindings = {@QueueBinding(
            value = @Queue(value = "queue2",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "exchange2"),
            key = {"routingKey2"})})
    public void message2(String msg, Message message, Channel channel){
        System.out.println("接收到的消息2:"+msg);
        try {
            //手动应答
            //basicAck应答
            //参数1：消息的唯一标识ID，是一个正整数，是mq来自增设置的
            //参数2：是否批量应答
            int i = 1/0;
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //e.printStackTrace();
            if (!message.getMessageProperties().isRedelivered()){
                try {
                    //basicNack不应答
                    //参数1：消息的唯一标识ID，是一个正整数，是mq来自增设置的
                    //参数2：是否批量应答
                    //参数3：是否重新排队
                    System.out.println("消息2第一次应答:未应答");
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            } else {
                //basicReject拒绝应答
                //参数1：消息的唯一标识ID，是一个正整数，是mq来自增设置的
                //参数2：是否重新排队
                try {
                    System.out.println("消息2第二次应答：拒绝应答");
                    channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
